{% extends "base.html" %}

{% block title %}申请记录 - 乒乓球培训管理系统{% endblock %}

{% block extra_css %}
<style>
    .page-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 8px;
        padding: 30px;
        margin-bottom: 30px;
    }

    .filters-card {
        background: white;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .application-item {
        background: white;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 15px;
        border-left: 4px solid #ddd;
        transition: all 0.3s ease;
    }

    .application-item:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 15px rgba(0,0,0,0.15);
    }

    .application-pending {
        border-left-color: #ffc107;
    }

    .application-approved {
        border-left-color: #28a745;
    }

    .application-rejected {
        border-left-color: #dc3545;
    }

    .application-terminated {
        border-left-color: #6c757d;
    }

    .coach-avatar-sm {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        object-fit: cover;
        border: 2px solid #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .status-badge {
        font-size: 0.8rem;
        padding: 4px 12px;
        border-radius: 15px;
        font-weight: 500;
    }

    .status-pending {
        background: #fff3cd;
        color: #856404;
        border: 1px solid #ffeaa7;
    }

    .status-approved {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .status-rejected {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .status-terminated {
        background: #e2e3e5;
        color: #383d41;
        border: 1px solid #d6d8db;
    }

    .coach-info h6 {
        color: #333;
        margin-bottom: 5px;
    }

    .coach-meta {
        color: #666;
        font-size: 0.9rem;
        margin-bottom: 10px;
    }

    .application-dates {
        background: #f8f9fa;
        border-radius: 6px;
        padding: 10px;
        margin-top: 10px;
        font-size: 0.85rem;
    }

    .date-item {
        margin-bottom: 5px;
    }

    .date-item:last-child {
        margin-bottom: 0;
    }

    .date-label {
        font-weight: 600;
        color: #666;
        display: inline-block;
        width: 80px;
    }

    .application-note {
        background: #f8f9fa;
        border-radius: 6px;
        padding: 12px;
        margin-top: 10px;
        font-size: 0.9rem;
        color: #333;
    }

    .note-label {
        font-weight: 600;
        color: #666;
        margin-bottom: 5px;
    }

    .response-note {
        background: #e7f3ff;
        border: 1px solid #b3d7ff;
        border-radius: 6px;
        padding: 12px;
        margin-top: 10px;
        font-size: 0.9rem;
    }

    .response-note.rejected {
        background: #ffeaea;
        border-color: #ffcccb;
    }

    .quick-actions {
        display: flex;
        gap: 8px;
        margin-top: 10px;
    }

    .btn-action {
        padding: 6px 12px;
        border-radius: 15px;
        font-size: 0.8rem;
        border: none;
    }

    .btn-detail {
        background: #007bff;
        color: white;
    }

    .btn-detail:hover {
        background: #0056b3;
        color: white;
    }

    .btn-cancel {
        background: #dc3545;
        color: white;
    }

    .btn-cancel:hover {
        background: #c82333;
        color: white;
    }

    .btn-reapply {
        background: #28a745;
        color: white;
    }

    .btn-reapply:hover {
        background: #218838;
        color: white;
    }

    .empty-state {
        text-align: center;
        padding: 80px 20px;
        color: #666;
    }

    .empty-state i {
        font-size: 5rem;
        color: #ddd;
        margin-bottom: 20px;
    }

    .filter-buttons .btn {
        margin: 3px;
        border-radius: 20px;
    }

    .stats-summary {
        background: white;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .stats-item {
        text-align: center;
        padding: 15px;
    }

    .stats-number {
        font-size: 1.5rem;
        font-weight: bold;
        display: block;
        margin-bottom: 5px;
    }

    .stats-pending { color: #ffc107; }
    .stats-approved { color: #28a745; }
    .stats-rejected { color: #dc3545; }
    .stats-total { color: #007bff; }

    .timeline-icon {
        display: inline-block;
        width: 20px;
        text-align: center;
        margin-right: 8px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面头部 -->
    <div class="row">
        <div class="col-12">
            <div class="page-header">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h2 class="mb-2">申请记录</h2>
                        <p class="mb-0 fs-5">查看您的所有教练申请记录和状态</p>
                    </div>
                    <div>
                        <a href="{{ url_for('student_coach.my_coaches') }}" class="btn btn-light me-2">
                            <i class="fas fa-users me-2"></i>我的教练
                        </a>
                        <a href="{{ url_for('student_coach.search') }}" class="btn btn-outline-light">
                            <i class="fas fa-search me-2"></i>搜索教练
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 统计摘要 -->
    <div class="row">
        <div class="col-12">
            <div class="stats-summary">
                <div class="row">
                    <div class="col-md-3 stats-item">
                        <span class="stats-number stats-total">{{ total }}</span>
                        <span>总申请数</span>
                    </div>
                    <div class="col-md-3 stats-item">
                        <span class="stats-number stats-pending">
                            {{ applications|selectattr('status', 'equalto', 'pending')|list|length if applications else 0 }}
                        </span>
                        <span>审核中</span>
                    </div>
                    <div class="col-md-3 stats-item">
                        <span class="stats-number stats-approved">
                            {{ applications|selectattr('status', 'equalto', 'approved')|list|length if applications else 0 }}
                        </span>
                        <span>已通过</span>
                    </div>
                    <div class="col-md-3 stats-item">
                        <span class="stats-number stats-rejected">
                            {{ applications|selectattr('status', 'equalto', 'rejected')|list|length if applications else 0 }}
                        </span>
                        <span>已拒绝</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 筛选器 -->
    <div class="row">
        <div class="col-12">
            <div class="filters-card">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-2">状态筛选</h6>
                        <div class="filter-buttons">
                            <a href="{{ url_for('student_coach.applications') }}"
                               class="btn btn-sm {{ 'btn-primary' if not status else 'btn-outline-primary' }}">
                                全部
                            </a>
                            <a href="{{ url_for('student_coach.applications', status='pending') }}"
                               class="btn btn-sm {{ 'btn-warning' if status == 'pending' else 'btn-outline-warning' }}">
                                审核中
                            </a>
                            <a href="{{ url_for('student_coach.applications', status='approved') }}"
                               class="btn btn-sm {{ 'btn-success' if status == 'approved' else 'btn-outline-success' }}">
                                已通过
                            </a>
                            <a href="{{ url_for('student_coach.applications', status='rejected') }}"
                               class="btn btn-sm {{ 'btn-danger' if status == 'rejected' else 'btn-outline-danger' }}">
                                已拒绝
                            </a>
                            <a href="{{ url_for('student_coach.applications', status='terminated') }}"
                               class="btn btn-sm {{ 'btn-secondary' if status == 'terminated' else 'btn-outline-secondary' }}">
                                已终止
                            </a>
                        </div>
                    </div>
                    <div class="text-muted">
                        共 {{ total }} 条记录
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 申请记录列表 -->
    {% if applications %}
    <div class="row">
        <div class="col-12">
            {% for application in applications %}
            <div class="application-item application-{{ application.status }}">
                <div class="row align-items-start">
                    <div class="col-md-1">
                        <img src="{{ application.coach.photo_url or url_for('static', filename='images/default-avatar.svg') }}"
                             alt="{{ application.coach.real_name }}" class="coach-avatar-sm">
                    </div>
                    <div class="col-md-6">
                        <div class="coach-info">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <h6>{{ application.coach.real_name }}</h6>
                                <span class="status-badge status-{{ application.status }}">
                                    {% if application.status == 'pending' %}
                                        <i class="fas fa-clock me-1"></i>审核中
                                    {% elif application.status == 'approved' %}
                                        <i class="fas fa-check-circle me-1"></i>已通过
                                    {% elif application.status == 'rejected' %}
                                        <i class="fas fa-times-circle me-1"></i>已拒绝
                                    {% elif application.status == 'terminated' %}
                                        <i class="fas fa-ban me-1"></i>已终止
                                    {% endif %}
                                </span>
                            </div>

                            <div class="coach-meta">
                                <span class="me-3">
                                    <i class="fas fa-trophy me-1"></i>
                                    {% if application.coach.coach_level == 'senior' %}高级教练
                                    {% elif application.coach.coach_level == 'middle' %}中级教练
                                    {% else %}初级教练{% endif %}
                                </span>
                                <span class="me-3">
                                    <i class="fas fa-venus-mars me-1"></i>
                                    {{ '男' if application.coach.gender == 'male' else '女' }}
                                </span>
                                <span class="text-success">
                                    <i class="fas fa-dollar-sign me-1"></i>￥{{ application.coach.hourly_rate or 0 }}/课时
                                </span>
                            </div>

                            {% if application.apply_note %}
                            <div class="application-note">
                                <div class="note-label">申请说明：</div>
                                {{ application.apply_note[:150] }}{% if application.apply_note|length > 150 %}...{% endif %}
                            </div>
                            {% endif %}

                            {% if application.response_note %}
                            <div class="response-note {{ 'rejected' if application.status == 'rejected' else '' }}">
                                <div class="note-label">
                                    <i class="fas fa-{{ 'check' if application.status == 'approved' else 'times' }}-circle me-1"></i>
                                    教练回复：
                                </div>
                                {{ application.response_note }}
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="application-dates">
                            <div class="date-item">
                                <span class="timeline-icon"><i class="fas fa-paper-plane text-primary"></i></span>
                                <span class="date-label">申请时间：</span>
                                {{ application.applied_at.strftime('%m月%d日 %H:%M') if application.applied_at }}
                            </div>
                            {% if application.responded_at %}
                            <div class="date-item">
                                <span class="timeline-icon">
                                    <i class="fas fa-{{ 'check' if application.status == 'approved' else 'times' }}-circle
                                       text-{{ 'success' if application.status == 'approved' else 'danger' }}"></i>
                                </span>
                                <span class="date-label">回复时间：</span>
                                {{ application.responded_at.strftime('%m月%d日 %H:%M') }}
                            </div>
                            {% endif %}
                            {% if application.terminated_at %}
                            <div class="date-item">
                                <span class="timeline-icon"><i class="fas fa-ban text-secondary"></i></span>
                                <span class="date-label">终止时间：</span>
                                {{ application.terminated_at.strftime('%m月%d日 %H:%M') }}
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    <div class="col-md-2 text-end">
                        <div class="quick-actions">
                            <a href="{{ url_for('student_coach.detail', coach_id=application.coach.id) }}"
                               class="btn btn-action btn-detail" title="查看教练详情">
                                <i class="fas fa-eye me-1"></i>详情
                            </a>

                            {% if application.status == 'pending' %}
                            <button type="button" class="btn btn-action btn-cancel"
                                    onclick="confirmCancel({{ application.id }}, '{{ application.coach.real_name }}')"
                                    title="取消申请">
                                <i class="fas fa-times me-1"></i>取消
                            </button>
                            {% elif application.status == 'rejected' %}
                            <a href="{{ url_for('student_coach.apply', coach_id=application.coach.id) }}"
                               class="btn btn-action btn-reapply" title="重新申请">
                                <i class="fas fa-redo me-1"></i>重申
                            </a>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <!-- 分页 -->
    {% if pagination and pagination.pages > 1 %}
    <div class="row">
        <div class="col-12">
            <nav aria-label="申请记录分页">
                <ul class="pagination justify-content-center">
                    {% if pagination.has_prev %}
                    <li class="page-item">
                        <a class="page-link" href="{{ url_for('student_coach.applications', page=pagination.prev_num, status=status) }}">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                    {% endif %}

                    {% for page_num in pagination.iter_pages() %}
                        {% if page_num %}
                            {% if page_num != pagination.page %}
                            <li class="page-item">
                                <a class="page-link" href="{{ url_for('student_coach.applications', page=page_num, status=status) }}">
                                    {{ page_num }}
                                </a>
                            </li>
                            {% else %}
                            <li class="page-item active">
                                <span class="page-link">{{ page_num }}</span>
                            </li>
                            {% endif %}
                        {% else %}
                        <li class="page-item disabled">
                            <span class="page-link">…</span>
                        </li>
                        {% endif %}
                    {% endfor %}

                    {% if pagination.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="{{ url_for('student_coach.applications', page=pagination.next_num, status=status) }}">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
        </div>
    </div>
    {% endif %}

    {% else %}
    <!-- 空状态 -->
    <div class="row">
        <div class="col-12">
            <div class="empty-state">
                <i class="fas fa-clipboard-list"></i>
                {% if status %}
                <h4>暂无{{ {'pending': '审核中', 'approved': '已通过', 'rejected': '已拒绝', 'terminated': '已终止'}[status] }}的申请</h4>
                <p class="text-muted">您当前没有{{ {'pending': '待审核', 'approved': '已通过', 'rejected': '被拒绝', 'terminated': '已终止'}[status] }}的教练申请</p>
                <a href="{{ url_for('student_coach.applications') }}" class="btn btn-primary">
                    <i class="fas fa-list me-2"></i>查看全部申请
                </a>
                {% else %}
                <h4>还没有申请记录</h4>
                <p class="text-muted">您还没有向任何教练发送过申请</p>
                <a href="{{ url_for('student_coach.search') }}" class="btn btn-primary btn-lg">
                    <i class="fas fa-search me-2"></i>搜索教练
                </a>
                {% endif %}
            </div>
        </div>
    </div>
    {% endif %}
</div>

<!-- 确认对话框 -->
<div class="modal fade" id="cancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">取消申请</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="cancelModalBody">
                确认要取消申请吗？
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmCancelBtn">确认取消</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentApplicationId = null;

$(document).ready(function() {
    // 应用项悬停效果
    $('.application-item').hover(
        function() {
            $(this).addClass('shadow');
        },
        function() {
            $(this).removeClass('shadow');
        }
    );

    // 确认取消按钮事件
    $('#confirmCancelBtn').click(function() {
        if (currentApplicationId) {
            cancelApplication(currentApplicationId);
        }
        $('#cancelModal').modal('hide');
    });
});

function confirmCancel(applicationId, coachName) {
    currentApplicationId = applicationId;

    $('#cancelModalBody').html(`
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            您确定要取消向 <strong>${coachName}</strong> 教练的申请吗？
        </div>
        <p class="mb-0">取消后：</p>
        <ul class="mb-0">
            <li>申请记录将被删除</li>
            <li>如需重新申请，需要重新填写申请信息</li>
        </ul>
    `);

    $('#cancelModal').modal('show');
}

function cancelApplication(applicationId) {
    // 显示加载状态
    $(`button[onclick*="${applicationId}"]`).html('<i class="fas fa-spinner fa-spin me-1"></i>取消中...')
                                             .prop('disabled', true);

    $.post(`{{ url_for('student_coach.cancel_application', relation_id=0) }}`.replace('0', applicationId))
        .done(function(response) {
            showMessage('申请已取消', 'success');
            setTimeout(function() {
                location.reload();
            }, 1500);
        })
        .fail(function(xhr) {
            let message = '取消失败，请重试';
            if (xhr.responseJSON && xhr.responseJSON.error) {
                message = xhr.responseJSON.error;
            }
            showMessage(message, 'error');

            // 恢复按钮状态
            $(`button[onclick*="${applicationId}"]`).html('<i class="fas fa-times me-1"></i>取消')
                                                     .prop('disabled', false);
        });
}

function showMessage(message, type) {
    const alertClass = type === 'success' ? 'alert-success' :
                      type === 'error' ? 'alert-danger' : 'alert-info';

    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 1050; min-width: 300px;" role="alert">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'times-circle' : 'info-circle'} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    $('body').append(alertHtml);

    setTimeout(function() {
        $('.alert').fadeOut(function() {
            $(this).remove();
        });
    }, 4000);
}

// 状态统计实时更新
function updateStatusStats() {
    // 这里可以添加实时更新统计数据的逻辑
    // 比如定期从API获取最新的申请状态统计
}
</script>
{% endblock %}